package com.jaws.core.mvc.feign;

import java.io.IOException;
import java.net.URI;
import java.util.Collection;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.feign.ribbon.CachingSpringLoadBalancerFactory;
import org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import feign.Client;
import feign.Request;
import feign.Response;

/**
 * feign扩展客户端
 * @author maojian
 * @date 2018-06-13 14:01:32
 * @since v1.0.0
 */
@Slf4j
public class JawsFeignClient extends LoadBalancerFeignClient {

	@Value("${spring.application.name:null}")
	private String applicationName;

	/**
	 * 调用方服务id
	 */
	private static final String UPSTREAM_SERVICE_ID = "upstream-service-id";
	/**
	 * 被调用方服务id
	 */
	private static final String DOWNSTREAM_SERVICE_ID = "downstream-service-id";

	public JawsFeignClient(Client delegate, CachingSpringLoadBalancerFactory lbClientFactory, SpringClientFactory clientFactory) {
		super(delegate, lbClientFactory, clientFactory);
	}

	@Override
	public Response execute(Request request, Request.Options options) throws IOException {
		URI asUri = URI.create(request.url());
		String serviceId = asUri.getHost();
		Map<String, Collection<String>> newHeader = Maps.newHashMap();
		newHeader.putAll(request.headers());
		newHeader.put(UPSTREAM_SERVICE_ID, Lists.newArrayList(applicationName));
		newHeader.put(DOWNSTREAM_SERVICE_ID, Lists.newArrayList(serviceId));

		Request newRequest = Request.create(request.method(), request.url(), newHeader, request.body(), request.charset());

		return super.execute(newRequest, options);
	}

}
